package com.heatingcharge.common.exception;

import com.heatingcharge.common.util.R;
import com.heatingcharge.common.util.ResponseCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 统一异常处理类
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
//    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    public R handle(Exception e) {
        if (e instanceof ParamException) {
            return R.error(ResponseCodeEnum.VALIDATE_FAIL.getCode(),e.getMessage());
        }else {
            log.error("【系统异常】{}", e.getMessage());
            return R.error(e.getMessage());
        }
    }

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BaseException.class)
    public R handleRRException(BaseException e) {
        return R.error(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(AccessDeniedException.class)
    public R handleAuthorizationException(AccessDeniedException e) {
        log.error(e.getMessage(), e);
        return R.error(403, "没有权限，请联系管理员授权");
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public R handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return R.error(404, "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(AccountExpiredException.class)
    public R handleAccountExpiredException(AccountExpiredException e) {
        log.error(e.getMessage(), e);
        return R.error(e.getMessage());
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public R handleUsernameNotFoundException(UsernameNotFoundException e) {
        log.error(e.getMessage(), e);
        return R.error(e.getMessage());
    }
}
